package com.huihui.activity.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.huihui.R;
import com.huihui.base.BaseActivity;
import com.huihui.datamanager.AppManager;
import com.huihui.eventbus.TestEvent;
import com.huihui.eventbus.WxLoginSuccess;
import com.huihui.network.HttpContants;
import com.huihui.network.OkHttpRequest;
import com.huihui.network.base.CallBackUtil;
import com.huihui.network.pojo.UserInfo;
import com.huihui.utils.Contants;
import com.huihui.utils.IntentUtils;
import com.huihui.utils.ShareUtils;
import com.huihui.utils.StringUtils;
import com.huihui.wxapi.WXEntryActivity;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AccessTokenKeeper;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbAppInfo;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;


public class LoginActivity extends BaseActivity implements View.OnClickListener{

    private TextView login_title;
    private EditText input_phone;
    private EditText input_psw;
    private TextView forget_psw;
    private TextView login;
    private TextView register;
    private TextView iphone_login;
    private ImageView wb_login;
    private ImageView wx_login;
    private int loginType = 1;

    private String WEIXIN_APPID = "wx9fb11f4d733cefb8";
    private IWXAPI api;

    /** 注意：SsoHandler 仅当 SDK 支持 SSO 时有效 */
    private SsoHandler mSsoHandler;

    private boolean mIsPhoneValid;
    private int mCount = 60;


    private Runnable mCountDownRunnable = new Runnable() {
        @Override
        public void run() {
            if (mCount > 0) {
                forget_psw.setText(getString(R.string.control_get_code_counter, mCount--));
                UIHandler.postDelayed(mCountDownRunnable, 1000);
            } else {
                mCount = 60;
                forget_psw.setText(getString(R.string.get_sms));
                if (mIsPhoneValid) {
                    forget_psw.setEnabled(true);
                }
            }
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login2);
        api = WXAPIFactory.createWXAPI(this, Contants.WEIXIN_APPID, false);
        api.registerApp(Contants.WEIXIN_APPID);
        EventBus.getDefault().register(this);
        initView();
        initListener();
        mSsoHandler = new SsoHandler(LoginActivity.this);
    }

    private void initListener() {
        forget_psw.setOnClickListener(this);
        login.setOnClickListener(this);
        register.setOnClickListener(this);
        iphone_login.setOnClickListener(this);//切换登录方式
        wb_login.setOnClickListener(this);
        wx_login.setOnClickListener(this);

        input_phone.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isPhone(input_phone.getText().toString())) {
                    if (mCount > 0 && mCount < 60) {
                        mIsPhoneValid = false;
                        forget_psw.setEnabled(false);
                    } else {
                        mIsPhoneValid = true;
                        forget_psw.setEnabled(true);
                    }
                } else {
                    mIsPhoneValid = false;
                    forget_psw.setEnabled(false);
                }

            }
        });
    }

    private void initView() {
        login_title = (TextView) findViewById(R.id.login_title);
        input_phone = (EditText) findViewById(R.id.input_phone);
        input_psw = (EditText) findViewById(R.id.input_psw);
        forget_psw = (TextView) findViewById(R.id.forget_psw);
        login = (TextView) findViewById(R.id.login);
        register = (TextView) findViewById(R.id.register);
        iphone_login = (TextView) findViewById(R.id.iphone_login);
        wb_login = (ImageView) findViewById(R.id.wb_login);
        wx_login = (ImageView) findViewById(R.id.wx_login);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.forget_psw:
                doForgetPsw();
                break;
            case R.id.login:
                doLogin();
                break;
            case R.id.register:
                IntentUtils.gotoRegisterActivity(this);
                break;
            case R.id.iphone_login:
                changeModel();
                break;
            case R.id.wb_login:
                otherLogin(1);
                break;
            case R.id.wx_login:
                otherLogin(2);
                break;
        }
    }

    private void otherLogin(int type) {
        if(type == 1){
            mSsoHandler.authorize(new SelfWbAuthListener());
        }else{
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "none";
            api.sendReq(req);
        }
    }

    /**
     * 当 SSO 授权 Activity 退出时，该函数被调用。
     *
     * @see {@link Activity#onActivityResult}
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // SSO 授权回调
        // 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResults
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }

    }

    private class SelfWbAuthListener implements com.sina.weibo.sdk.auth.WbAuthListener{
        @Override
        public void onSuccess(final Oauth2AccessToken token) {
            String accessToken = token.getToken();
            String uid = token.getUid();
           AuthInfo authInfo = WbSdk.getAuthInfo();
           if(authInfo == null){
               return;
           }

            OkHttpRequest.getInstance().getWbInfo(authInfo.getAppKey(),accessToken, uid, new CallBackUtil.CallBackString() {
                @Override
                public void onFailure(Call call, Exception e) {
                    Log.e("dm","");
                }

                @Override
                public void onResponse(String response) {
                    try {
                        int sex = 0;
                        JSONObject json = new JSONObject(response);
                        final String screen_name  = json.getString("screen_name");
                        final String profile_image_url = json.getString("profile_image_url");
                        String gender  = json.getString("gender");
                        if(gender.equals("m")){
                            sex = 1;
                        }else{
                            sex = 0;
                        }
                        Log.e("dm","");
                        final int finalSex = sex;
                        LoginActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                OkHttpRequest.getInstance().saveUserByPlatform(HttpContants.saveUserByPlatform, token.getUid(), screen_name, profile_image_url, finalSex,2, new CallBackUtil.CallBackString() {
                                    @Override
                                    public void onFailure(Call call, Exception e) {
                                        Log.e("","");
                                    }

                                    @Override
                                    public void onResponse(String response) {
                                        try {
                                            JSONObject json = new JSONObject(response);
                                            if(json.has(HttpContants.DATA)){
                                                UserInfo userInfo = AppManager.getGson().fromJson(json.getString(HttpContants.DATA),UserInfo.class);
                                                if(userInfo != null) {
                                                    if(userInfo.getUser_type() == 2){
                                                        finish();
                                                    }else {
                                                        Log.d("token", "登录成功返回的token = " + userInfo.getToken());
                                                        AppManager.setUserInfo(userInfo);
                                                        AppManager.setToken(userInfo.getToken());
                                                        EventBus.getDefault().post(new WxLoginSuccess());
                                                        finish();
                                                    }
                                                }
                                            }else {
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            }
                        });

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });

        }

        @Override
        public void cancel() {
        }

        @Override
        public void onFailure(WbConnectErrorMessage errorMessage) {

        }
    }

    private void doForgetPsw() {
        if(loginType == 1){
            IntentUtils.gotoReSetPswActivity(getContext(),0);
        }else{
            //获取验证码，并开启倒计时
            getSms();
        }
    }

    private void getSms() {
        //获取验证码
        String inputPhone = input_phone.getText().toString();
        if (!StringUtils.isPhone(inputPhone)) {
            Toast.makeText(getContext(),R.string.error_phone_not_match,Toast.LENGTH_SHORT).show();
            return;
        }
        forget_psw.setEnabled(false);
        forget_psw.setText(getString(R.string.control_get_code_counter, mCount--));
        //获取验证码请求
        OkHttpRequest.getInstance().sendSmsCode(HttpContants.sendSmsCode, 0, input_phone.getText().toString(), 0, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {
                forget_psw.setEnabled(true);
                mCount = 60;
                forget_psw.setText(getString(R.string.get_sms));
                UIHandler.removeCallbacks(mCountDownRunnable);
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    if(json.has(HttpContants.MSG)){
                        Toast.makeText(getContext(), json.getString(HttpContants.MSG),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        UIHandler.postDelayed(mCountDownRunnable, 1000);
    }

    private void changeModel() {
        if(loginType == 1){
            loginType = 2;
            login_title.setText(R.string.iphone_login);
            input_psw.setHint(R.string.input_sms);
            forget_psw.setText(R.string.get_sms);
            iphone_login.setText(R.string.psw_login);
            forget_psw.setEnabled(true);
            return;
        }else{
            loginType = 1;
            login_title.setText(R.string.psw_login);
            input_psw.setHint(R.string.input_psw);
            forget_psw.setText(R.string.forget_psw);
            iphone_login.setText(R.string.iphone_login);
            UIHandler.removeCallbacks(mCountDownRunnable);
            forget_psw.setEnabled(true);
            return;
        }
    }

    /**
     * 登陆  先判断手机号和密码
     */
    private void doLogin() {
        if(loginType == 1){
            //密码登陆
            login(1);
        }else{
            //验证码登陆
            login(2);
        }
    }

    private void login(int i) {
        String inputPhone = input_phone.getText().toString();
        //登陆
        if (!StringUtils.isPhone(inputPhone)) {
            Toast.makeText(getContext(),R.string.error_phone_not_match,Toast.LENGTH_SHORT).show();
            return;
        }
        String psw = input_psw.getText().toString();
        if(psw.length() < 6){
            Toast.makeText(getContext(),"密码不能少于6位数",Toast.LENGTH_SHORT).show();
            return;
        }
        if(i == 1)
            OkHttpRequest.getInstance().login(HttpContants.login, inputPhone, psw, "", 0, new CallBackUtil.CallBackString() {
                @Override
                public void onFailure(Call call, Exception e) {
                    Log.e(TAG, e.toString());
                }

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject json = new JSONObject(response);
                        if(json.has(HttpContants.STATE) && json.getInt(HttpContants.STATE) == 10000){
                        if (json.has(HttpContants.DATA)) {
                            UserInfo userInfo = AppManager.getGson().fromJson(json.getString(HttpContants.DATA), UserInfo.class);
                            if (userInfo != null) {
                                int user_type = userInfo.getUser_type();
                                if(user_type != 2){

                                    setUserInfo(userInfo);
                                    Log.d("token", "登录成功返回的token = " + userInfo.getToken());
                                    AppManager.setUserInfo(userInfo);
                                    AppManager.setToken(userInfo.getToken());
                                    IntentUtils.gotoMainActivity(getContext());
                                    finish();
                                }else {

                                }
                            }
                        } else {
                            Log.e(TAG, response);
                        }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        else{
            OkHttpRequest.getInstance().login(HttpContants.login, inputPhone, "", psw, 1, new CallBackUtil.CallBackString() {
                @Override
                public void onFailure(Call call, Exception e) {
                    Log.e(TAG,e.toString());
                }

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject json = new JSONObject(response);
                        if(json.has(HttpContants.STATE) && json.getInt(HttpContants.STATE) == 10000) {
                            if (json.has(HttpContants.DATA)) {
                                UserInfo userInfo = AppManager.getGson().fromJson(json.getString(HttpContants.DATA), UserInfo.class);
                                if (userInfo != null) {
                                    int user_type = userInfo.getUser_type();
                                    if(user_type != 2){

                                        setUserInfo(userInfo);
                                        AppManager.setUserInfo(userInfo);
                                        AppManager.setToken(userInfo.getToken());
                                        AppManager.setToken(userInfo.getToken());
                                        IntentUtils.gotoMainActivity(getContext());
                                        finish();
                                    }
                                }
                            } else {
                                Log.e(TAG, response);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(WxLoginSuccess wxLoginSuccess) {
        if(wxLoginSuccess != null){
            IntentUtils.gotoMainActivity(this);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
